package cn.yangliu.task.locker;

import cn.yangliu.task.config.TaskClusterProperties;
import cn.yangliu.task.lock.Locker;
import cn.yangliu.task.utils.RedisLockUtils;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


public class RedisLocker implements Locker {

    @Autowired
    private TaskClusterProperties properties;

    @Autowired
    private JedisPool jedisPool;

    @Override
    public boolean lock(String lockKey, String value) {
        boolean lock;
        try (Jedis jedis = jedisPool.getResource()) {
            lock = RedisLockUtils.lock(jedis, lockKey, value, properties.getLockExpireTime());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return lock;
    }

    @Override
    public void unlock(String lockKey, String value) {
        if (properties.isReleaseLock()) {
            try (Jedis jedis = jedisPool.getResource()) {
                RedisLockUtils.unlock(jedis, lockKey, value);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }
}
